package com.zyl.widget.timer;

import java.util.TimerTask;

import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.os.PowerManager;
import android.os.Vibrator;
import android.os.PowerManager.WakeLock;

public class MyTimerTask extends TimerTask {
		int appWidgetId;
		AppWidgetManager appWidgetManager;
		Context context;

		public MyTimerTask(Context paramContext,
				AppWidgetManager paramAppWidgetManager, int appWidgetId ) {
			this.context = paramContext;
			this.appWidgetManager = paramAppWidgetManager;
			this.appWidgetId = appWidgetId;
			acquireWakeLock();
		}

	public void run() {
		if (BaseWidget.time <= 0) {
			releaseWakeLock();
			Vibrator vibrator = (Vibrator)  context.getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(500);
			this.cancel();
			BaseWidget.time=0;
		}else{
			BaseWidget.time--;
		}
		
		
		BaseWidget.updateAppWidget(this.context, this.appWidgetManager,
				this.appWidgetId);
		
	}
		
		
		
		private static WakeLock wakeLock = null; //占用cpu的锁
		 
		/**
		 * 获取电源管理锁，占用CPU使不休眠
		 */
		private void acquireWakeLock() {
		   if (wakeLock == null) {
		       PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		       wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getCanonicalName());
		       wakeLock.acquire();
		   }
		 }
		 /**
		 * 释放电源管理锁，使不占用cpu
		 */
		private void releaseWakeLock() {
		      if (wakeLock != null && wakeLock.isHeld()) {
		           wakeLock.release();
		           wakeLock = null;
		      }
		}
	}